package com.css.apps.base.common.util;

import com.css.apps.base.dict.model.SDict;
import com.css.apps.base.dict.service.DictMan;
import com.css.util.ListUtil;
import com.css.util.StringHelper;
import com.opensymphony.webwork.ServletActionContext;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ExportExcelUtil {

	public static void exportExcel(String fileName, List<Object[]> list, List<String> headList, List<String> typeList,
								   List<Integer> widthList, HttpServletRequest request, HttpServletResponse response) {

		ServletOutputStream fout = null;
		try {
			if (StringHelper.isNotEmpty(request.getHeader("User-Agent"))) {
				if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
					fileName = URLEncoder.encode(fileName, "UTF-8");
				else if (request.getHeader("User-Agent").toUpperCase().indexOf("Mozilla") > 0)
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				else {
					fileName = URLEncoder.encode(fileName, "UTF-8");
				}

			}
			response.reset();
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0L);
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			int size = list.size();
			HSSFWorkbook wb = new HSSFWorkbook();
			int rowsOfSheet = 3000; // 每个sheet的行数
			int sheets = 1;
			if (size > rowsOfSheet) {
				sheets = size % rowsOfSheet != 0 ? size / rowsOfSheet + 1 : size / rowsOfSheet;
			}
			for (int j = 0; j < sheets; j++) {
				HSSFSheet sheet = wb.createSheet("表" + j);

				HSSFFont font = wb.createFont();
				font.setFontHeightInPoints((short) 16);
				font.setFontName("黑体");

				HSSFFont font1 = wb.createFont();
				font1.setFontHeightInPoints((short) 10);
				font1.setFontName("黑体");

				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HorizontalAlignment.CENTER);
				style.setFont(font);

				HSSFCellStyle style1 = wb.createCellStyle();
				style1.setAlignment(HorizontalAlignment.CENTER);
				style1.setFont(font1);
				style.setWrapText(true);

				HSSFRow row = sheet.createRow((int) 0);
				HSSFCell cell = null;

				for (int i = 0; i < headList.size(); i++) {
					cell = row.createCell(i);
					cell.setCellStyle(style);
					cell.setCellValue(headList.get(i));
				}

				int k = rowsOfSheet;
				if (size % rowsOfSheet != 0 && j == (size / rowsOfSheet)) {
					k = size % rowsOfSheet;
				}

				if (list != null && list.size() > 0) {
					for (int i = 0; i < k; i++) {
						row = sheet.createRow((int) i + 1);
						Object[] obj = list.get(rowsOfSheet * j + i);

						for (int c = 0; c < obj.length; c++) {
							cell = row.createCell(c);
							cell.setCellStyle(style1);
							if ("0".equals(typeList.get(c))) {
								cell.setCellType(CellType.NUMERIC);
								cell.setCellValue((Long) obj[c]);
							} else if ("1".equals(typeList.get(c))) {
								cell.setCellType(CellType.STRING);
								cell.setCellValue((String) obj[c]);
							} else if ("2".equals(typeList.get(c))) {
								cell.setCellType(CellType.STRING);
								if (obj[c] != null && !(obj[c]).equals("null")) {
									cell.setCellValue(sdf.format((Date) obj[c]));
								}
							} else if ("3".equals(typeList.get(c))) {
								cell.setCellType(CellType.NUMERIC);
								cell.setCellValue(Double.valueOf((String) obj[c]));
							} else {
								cell.setCellType(CellType.STRING);
								SDict d = DictMan.getDictType(typeList.get(c), String.valueOf(obj[c]));
								if (d == null) {
									cell.setCellValue("");
								} else {
									cell.setCellValue(
											DictMan.getDictType(typeList.get(c), String.valueOf(obj[c])).getName());
								}
							}
						}
					}
				}

				if (widthList != null && widthList.size() > 0) {
					for (int w = 0; w < widthList.size(); w++) {
						sheet.setColumnWidth(w, widthList.get(w));
					}
				}
			}
			fout = response.getOutputStream();
			wb.write(fout);
			fout.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fout != null) {
				try {
					fout.close();
					fout = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void exportExcel(String fileName, Map<String, List<Object[]>> dataMap, Map<String, List<String>> headMap,
								   Map<String, List<String>> typeMap, Map<String, List<Integer>> widthMap) {
		
		ServletOutputStream fout = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			HSSFWorkbook wb = new HSSFWorkbook();
			
			Set<String> keySet = dataMap.keySet();
			if (keySet != null) {
				for (String key : keySet) {
					HSSFSheet sheet = wb.createSheet(key);
					
					HSSFFont titleFont = wb.createFont();
					titleFont.setFontHeightInPoints((short) 16);
					titleFont.setFontName("黑体");
					
					HSSFFont textFont = wb.createFont();
					textFont.setFontHeightInPoints((short) 10);
					textFont.setFontName("黑体");
					
					HSSFCellStyle titleStyle = wb.createCellStyle();
					titleStyle.setAlignment(HorizontalAlignment.CENTER);
					titleStyle.setFont(titleFont);
					
					HSSFCellStyle textStyle = wb.createCellStyle();
					textStyle.setAlignment(HorizontalAlignment.CENTER);
					textStyle.setFont(textFont);
					titleStyle.setWrapText(true);
					
					HSSFRow title = sheet.createRow((int) 0);
					HSSFCell cell = null;
					List<String> headList = headMap.get(key);
					for (int i = 0; i < headList.size(); i++) {
						cell = title.createCell(i);
						cell.setCellStyle(titleStyle);
						cell.setCellValue(headList.get(i));
					}
					List<Object[]> datas = dataMap.get(key);
					if (ListUtil.isLstNotEmpty(datas)) {
						for (int i = 0; i < datas.size(); i++) {
							HSSFRow row = sheet.createRow(i + 1);
							Object[] data = datas.get(i);
							for (int j = 0; j < data.length; j++) {
								cell = row.createCell(j);
								cell.setCellStyle(textStyle);
								List<String> typeList = typeMap.get(key);
								if ("0".equals(typeList.get(j))) {
									cell.setCellType(CellType.NUMERIC);
									cell.setCellValue((Long) data[j]);
								} else if ("1".equals(typeList.get(j))) {
									cell.setCellType(CellType.STRING);
									cell.setCellValue((String) data[j]);
								} else if ("2".equals(typeList.get(j))) {
									cell.setCellType(CellType.STRING);
									if (data[j] != null && !(data[j]).equals("null")) {
										cell.setCellValue(sdf.format((Date) data[j]));
									}
								} else {
									cell.setCellType(CellType.STRING);
									SDict d = DictMan.getDictType(typeList.get(j), String.valueOf(data[j]));
									if (d == null) {
										cell.setCellValue("");
									} else {
										cell.setCellValue(DictMan.getDictType(typeList.get(j), String.valueOf(data[j])).getName());
									}
								}
							}
						}
					}
					List<Integer> widthList = widthMap.get(key);
					if (ListUtil.isLstNotEmpty(widthList)) {
						for (int w = 0; w < widthList.size(); w++) {
							sheet.setColumnWidth(w, widthList.get(w));
						}
					}
				}
			}
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = ServletActionContext.getRequest();
			if (StringHelper.isNotEmpty(request.getHeader("User-Agent"))) {
				if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
					fileName = URLEncoder.encode(fileName, "UTF-8");
				else if (request.getHeader("User-Agent").toUpperCase().indexOf("Mozilla") > 0)
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				else {
					fileName = URLEncoder.encode(fileName, "UTF-8");
				}
				
			}
			response.reset();
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0L);
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
			fout = response.getOutputStream();
			wb.write(fout);
			fout.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fout != null) {
				try {
					fout.close();
					fout = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void exportExcel(String fileName, List<Object[]> list, List<String> headList, List<String> typeList,
			List<Integer> widthList, HttpServletRequest request, HttpServletResponse response, int sheetSize) {

		ServletOutputStream fout = null;
		try {
			if (StringHelper.isNotEmpty(request.getHeader("User-Agent"))) {
				if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
					fileName = URLEncoder.encode(fileName, "UTF-8");
				else if (request.getHeader("User-Agent").toUpperCase().indexOf("Mozilla") > 0)
					fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				else {
					fileName = URLEncoder.encode(fileName, "UTF-8");
				}

			}
			response.reset();
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0L);
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			int size = list.size();
			HSSFWorkbook wb = new HSSFWorkbook();
			int rowsOfSheet = 3000; // 每个sheet的行数
			for (int j = 0; j < sheetSize; j++) {
				HSSFSheet sheet = wb.createSheet("表" + j);

				HSSFFont font = wb.createFont();
				font.setFontHeightInPoints((short) 16);
				font.setFontName("黑体");

				HSSFFont font1 = wb.createFont();
				font1.setFontHeightInPoints((short) 10);
				font1.setFontName("黑体");

				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HorizontalAlignment.CENTER);
				style.setFont(font);

				HSSFCellStyle style1 = wb.createCellStyle();
				style1.setAlignment(HorizontalAlignment.CENTER);
				style1.setFont(font1);

				HSSFCellStyle style2 = wb.createCellStyle();
				style1.setAlignment(HorizontalAlignment.LEFT);
				style1.setFont(font1);

				HSSFRow row = sheet.createRow((int) 0);
				HSSFCell cell = null;

				for (int i = 0; i < headList.size(); i++) {
					cell = row.createCell(i);
					cell.setCellStyle(style);
					cell.setCellValue(headList.get(i));
				}

				int k = rowsOfSheet;
				if (size % rowsOfSheet != 0 && j == (size / rowsOfSheet)) {
					k = size % rowsOfSheet;
				}

				if (list != null && list.size() > 0) {
					for (int i = 0; i < k; i++) {
						row = sheet.createRow((int) i + 1);
						Object[] obj = list.get(rowsOfSheet * j + i);

						for (int c = 0; c < obj.length; c++) {
							cell = row.createCell(c);
							cell.setCellStyle(style2);
							if ("0".equals(typeList.get(c))) {
								cell.setCellType(CellType.NUMERIC);
								cell.setCellValue((Double) obj[c]);
							} else if ("1".equals(typeList.get(c))) {
								cell.setCellType(CellType.STRING);
								cell.setCellValue((String) obj[c]);
							} else if ("2".equals(typeList.get(c))) {
								cell.setCellType(CellType.STRING);
								if (obj[c] != null && !(obj[c]).equals("null")) {
									cell.setCellValue(sdf.format((Date) obj[c]));
								}
							} else {
								cell.setCellType(CellType.STRING);
								SDict d = DictMan.getDictType(typeList.get(c), String.valueOf(obj[c]));
								if (d == null) {
									cell.setCellValue("");
								} else {
									cell.setCellValue(d.getName());
								}
							}
						}
					}
				}

				if (widthList != null && widthList.size() > 0) {
					for (int w = 0; w < widthList.size(); w++) {
						sheet.setColumnWidth(w, widthList.get(w));
					}
				}
			}
			fout = response.getOutputStream();
			wb.write(fout);
			fout.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fout != null) {
				try {
					fout.close();
					fout = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
